//
//  XLDataBaseManager.m
//  DaoNativeSave
//
//  Created by tanqilong on 16/7/11.
//  Copyright © 2016年 tanqilong. All rights reserved.
//

#import "XLDataBaseManager.h"
#import "FMDB.h"
#import <CommonCrypto/CommonDigest.h>

@interface XLDataBaseManager ()
@property (nonatomic,copy) NSString * url;
@property (nonatomic,strong) FMDatabase * db;
@end

@implementation XLDataBaseManager

-(instancetype)initWithDataBaseUrl:(NSString *)url {
    self = [super init];
    if (self) {
        _url = url;
        [self createDataBase];
    }
    return self;
}

//创建数据库
-(void)createDataBase{
    if (_url == nil) {
        //创建数据库
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        _url = [docsPath stringByAppendingPathComponent:@"NetDataBase.db"];
    }
    _db = [FMDatabase databaseWithPath:_url];
    if ([_db open]) {
        NSLog(@"数据库打开成功,地址:%@",_url);
        //建立表格
        NSString *sqlCreateTable =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (hashCode INTEGER,md5Code INTEGER, requestStr TEXT,value TEXT, PRIMARY KEY(hashCode,md5Code))",NetRequestTable];
        BOOL res = [_db executeUpdate:sqlCreateTable];
        if (!res) {
            NSLog(@"error when creating db table");
        } else {
            NSLog(@"success to creating db table");
        }
    }
}

#pragma mark --插入数据
-(void)insertDataToNetTableWithUrlStr:(NSString *)urlStr Value:(NSString *)value CompleteBlock:(void (^)(BOOL))completeBlock {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        BOOL isSuccess = [self insertDataToNetTableWithUrlStr:urlStr Value:value];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completeBlock) {
                completeBlock(isSuccess);
            }
        });
    });
}

-(BOOL)insertDataToNetTableWithUrlStr:(NSString *)urlStr Value:(NSString *)value{
    if (urlStr == nil && [urlStr isEqualToString:@""]) {
        return nil;
    }
    NSInteger hashCode = [urlStr hash];
    NSInteger md5Hash = [[self md5:urlStr]hash];
    return [self insertDataToNetTableWithHashCode:hashCode Md5Code:md5Hash UrlStr:urlStr value:value];
}

-(BOOL)insertDataToNetTableWithHashCode:(NSInteger)hashCode Md5Code:(NSInteger)md5Code UrlStr:(NSString *)urlStr value:(NSString *)date {
//    NSString * valueStr = [self changeDataToString:date];
    NSString * insertStr = [NSString stringWithFormat:@"REPLACE into %@(hashCode,md5Code,requestStr,value) values (%lu,%lu,'%@','%@')",NetRequestTable,hashCode,md5Code,urlStr,date];
    BOOL res;
    if ([_db open]) {
        res = [_db executeUpdate:insertStr];
        if (res) {
             NSLog(@"插入数据成功");
        }
        [_db close];
    }
    return res;
}

#pragma mark --查询数据
-(void)selectValueDataByNetTableWithUrlStr:(NSString *)urlStr CompleteBlock:(void (^)(NSString *))completeBlock {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString * data = [self selectValueDataByNetTableWithUrlStr:urlStr];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completeBlock) {
                completeBlock(data);
            }
        });
    });
}

-(NSString *)selectValueDataByNetTableWithUrlStr:(NSString *)urlStr {
    if (urlStr == nil && [urlStr isEqualToString:@""]) {
        return nil;
    }
    NSInteger hashCode = [urlStr hash];
    NSInteger md5Hash = [[self md5:urlStr]hash];
    return [self getValueByNetTableWithHashCode:hashCode Md5Code:md5Hash UrlStr:urlStr];
}

-(NSString *)getValueByNetTableWithHashCode:(NSInteger)hashCode Md5Code:(NSInteger)md5Code UrlStr:(NSString *)urlStr {
    NSString * selectStr = [NSString stringWithFormat:@"SELECT requestStr,value FROM %@ where hashCode = %lu and md5Code = %lu",NetRequestTable,hashCode,md5Code];
    NSString * data = nil;
    if ([_db open]) {
        FMResultSet * resultset = [_db executeQuery:selectStr];
        if ([resultset next]) {
            NSString * url = [resultset stringForColumn:@"requestStr"];
            if ([url isEqualToString:urlStr]) {
                data = [resultset stringForColumn:@"value"];
//                valueStr = [nsst]
//                data = [valueStr dataUsingEncoding:kCFStringEncodingUTF8];
            }
            else {
                NSLog(@"查询的编码与字符串不匹配");
            }
        }
        [_db close];
    }
    return data;
}

-(void)clean:(void (^)(BOOL))complete {
    NSString * str = [NSString stringWithFormat:@"drop table %@",NetRequestTable];
    if ([_db open]) {
        BOOL isSuccess = [_db executeUpdate:str];
        complete(isSuccess);
        [_db close];
    }
    else {
        complete(NO);
    }
}

//数据转字符串
-(NSString *)changeDataToString:(NSData *)data {
    NSString * valueStr = [[NSString alloc] initWithData:data encoding:kCFStringEncodingUTF8];
    return valueStr;
}

- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


@end
